package com.data.king.tenda.service;

import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.util.Log;

import java.util.Date;

/**
 * 后台定时任务执行器 使用AlarmManager
 * Created by lenovo on 2018/1/12.
 */
public class BackendService extends Service {
    private  static final String TAG = "LongRunningService";
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
//        //启用前台服务，主要是startForeground()
//        Notification notification = new Notification(android.R.drawable.sym_def_app_icon, "数据采集开始啦！", System.currentTimeMillis());
//        //设置通知默认效果
//        notification.flags = Notification.FLAG_SHOW_LIGHTS;
//        startForeground(1, notification);
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG,"定时任务执行开始");
                Util.getAsynHttp();
                Log.d(TAG, "定时任务执行结束 executed at " + new Date().toString());
            }
        }).start();
        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        int delayTiem =  180 * 1000; // 这是设置执行时间的毫秒数
        long triggerAtTime = SystemClock.elapsedRealtime() + delayTiem;
        Intent i = new Intent(this, AlarmReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
        //manager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pi);
        return super.onStartCommand(intent, flags, startId);
    }

}
